﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;

namespace Demo.Controls
{
    public class FileContent
    {
         private String m_Filename= default(String);
					public String Filename
					{
						get
						{
							return m_Filename;
						}
						set
						{
							m_Filename = value;
						}
					} 

         private String m_Content= default(String);
					public String Content
					{
						get
						{
							return m_Content;
						}
						set
						{
							m_Content = value;
						}
					}

                    public String Id
                    {
                        get
                        {
                            return Filename.Replace(".", "_");
                        }
                    }
    }

    public partial class CodeBrowser : System.Web.UI.UserControl
    {
        private String m_FilterRegex = default(String);
        public String FilterRegex
        {
            get
            {
                return m_FilterRegex;
            }
            set
            {
                m_FilterRegex = value;
            }
        }

        public int SumOfLines
        {
            get 
            {
                int count = 0;
                foreach (FileContent file in Files)
                {
                    count += file.Content.Split('\n').Count();
                }

                return count;
            }
        }

        private List<FileContent> m_Files = default(List<FileContent>);
        private bool m_Files_calculated = false;
        public List<FileContent> Files
        {
            get
            {
                if (!m_Files_calculated)
                {
                    m_Files = new List<FileContent>();

                    Regex regex = new Regex(FilterRegex, RegexOptions.Compiled | RegexOptions.Singleline);

                    String directory = this.Page.Server.MapPath(this.Page.Request.AppRelativeCurrentExecutionFilePath);
                    directory = directory.Substring(0, directory.LastIndexOf('\\'));
                    foreach (String file in Directory.GetFiles(directory))
                    {
                        if (!regex.IsMatch(file))
                        {
                            continue;
                        }

                        String name = file.Substring(file.LastIndexOf('\\') + 1);

                        m_Files.Add(new FileContent() { Content = File.ReadAllText(file), Filename = name });
                    }

                    m_Files_calculated = true;
                }

                return m_Files;
            }
        }    
    }
}